using System;
using System.Net;

namespace DotNetNukeMVPWizard.ProjectConfiguration
{
    public class UrlAddressConfiguration : TextConfiguration
    {
        #region Constructors
        public UrlAddressConfiguration(string key)
            : base(key)
        {
        }

        public UrlAddressConfiguration(string key, string errorReason)
            : base(key, errorReason)
        {            
        }

        public UrlAddressConfiguration(string key, string errorReason, bool isOptional)
            : base(key, errorReason, isOptional)
        {
        }         
        #endregion

        #region Property Overrides
        public override string Value
        {
            get { return base.Value; }
            set
            {
                if (!string.IsNullOrEmpty(value) && !value.EndsWith(@"/"))
                    value += @"/";
                base.Value = value;
            }
        }

        public override bool IsValid
        {
            get
            {
                bool _isValid = true;
                _isValid = (IsOptional && string.IsNullOrEmpty(Value)) || IsValidLocalHostUrl(Value);
                return _isValid;
            }
        }
        #endregion

        #region Private Validation Methods
        private static bool IsValidLocalHostUrl(string hostname)
        {
            bool success = false;
            try
            {
                Uri urlCheck = new Uri(hostname, UriKind.Absolute);
                if (urlCheck.IsAbsoluteUri && urlCheck.Scheme == Uri.UriSchemeHttp &&
                    urlCheck.IsLoopback && !urlCheck.IsFile && !urlCheck.IsUnc &&
                    string.IsNullOrEmpty(urlCheck.Fragment) && string.IsNullOrEmpty(urlCheck.Query) &&
                    IsFinalSegmentFolder(urlCheck.Segments))
                {
                    HttpWebRequest request = WebRequest.Create(urlCheck) as HttpWebRequest;
                    // TODO: (low priority) Consider a way to make this configurable by the end-user
                    request.Timeout = 30000; // 30 seconds timeout
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                            success = true;
                    }
                }
            }
            catch (Exception e)
            {
            }
            return success;
        }
        private static bool IsFinalSegmentFolder(string[] segments)
        {
            bool isFolder = false;
            if (segments != null && segments.Length > 0 &&
                !segments[segments.Length - 1].Contains(".") &&
                !segments[segments.Length - 1].Equals("/"))
                isFolder = true;
            return isFolder;
        }
        #endregion
    }
}
